#include "PlayerUtilityPrivate.h"
#include "PlayerUtility.h"
#include "volumeKey/volumeKey.h"
#include <QDebug>
//#include "tonePlayer/TonePlayer.h"

//TSS001596_-_Volume_level_range_in_Nokia_N8
//In previous S60 device models, the range of volume setting for audio playback has typically been from 0 (mute) to 10 (max. volume).
//In Nokia N8, the range is [0..10000]. Applications that rely on hard-coded values for volume will experience problems, such as playback volume being too low.

const TInt VOLBARRANGE = 10;
const TInt VOLBARSTEP = 1;

// ---------------------------------------------------------
// PlayerUtility::PlayerUtility()
// Constructor
// ---------------------------------------------------------
//
PlayerUtility::PlayerUtility(const QString& aFileName, QObject *parent, int initialVolume)
 : QObject(parent),iVolume(initialVolume)
{
    qDebug()<<"PlayerUtility create";
    TPtrC myDescriptor (reinterpret_cast<const TText*>(aFileName.constData()),aFileName.length());
#ifdef Q_OS_SYMBIAN
    d_ptr = CPlayerUtilityPrivate::NewL( myDescriptor, this);
#endif
    //iTonePlayer = new TonePlayer(this);

    //connect(iTonePlayer,SIGNAL(soundDeviceInUse()),this,SLOT(stop()));
}

// ---------------------------------------------------------
// PlayerUtility::~PlayerUtility()
// Destructor
// ---------------------------------------------------------
//
PlayerUtility::~PlayerUtility()
{
    delete d_ptr;
}

void PlayerUtility::play()
{
    qDebug()<<"PlayerUtility play";
    //setVolume(iVolume);
    d_ptr->Play();
    //iTonePlayer->play();
}

void PlayerUtility::stop()
{
    d_ptr->Stop();
    //iTonePlayer->stop();
}

void PlayerUtility::volumeKeyPressed(int upOrDown)
{
    int volume;
    d_ptr->GetVolume(volume);
    qDebug()<<"current volume"<<volume;
    TInt maxVolme = d_ptr->MaxVolume();
    //the Max volume of N8 is 10000
    volume = volume*VOLBARRANGE/maxVolme;

    switch(upOrDown)
    {
    case EVolumeDown:
        volume -= VOLBARSTEP;
        break;
    case EVolumeUp:
        volume += VOLBARSTEP;
        break;
    }
    if(volume>VOLBARRANGE)
        volume =VOLBARRANGE;
    if(volume<0)
        volume =0;

    qDebug()<<"volumeKeyPressed volume"<<volume;

    setVolume(volume);
}

void PlayerUtility::setVolume(int volume)
{
    TInt maxVolme = d_ptr->MaxVolume();
    qDebug()<<"MaxVolume = "<<maxVolme;
    //the Max volume of N8 is 10000
    int localVolume  = (maxVolme / VOLBARRANGE) * volume;
    qDebug()<<"set = "<<localVolume;
    d_ptr->SetVolume(localVolume);

    emit volumeChanged(volume);
}
